/* ========================================================================= */
/* интерактивный обработчик полей ввода                                      */
/* @autor Gorhover Dmitriy                                                   */
/* --------------------------------------------------------------------------*/
/*	interactiveValidator.init({                                              */
/*		phone: ['notice_phone'],                                             */
/*		amt: ['amt'],                                                        */
/*		number: ['b_card_or_acc']                                            */
/*	});                                                                      */
/* ========================================================================= */

var interactiveValidator = {
	input: [],
    private: {
        getChar: function(event) {
            if (event.which == null) {
                if (event.keyCode < 32) {
                    return null;
                }
                return String.fromCharCode(event.keyCode) /* IE */
            }
            if (event.which!=0 && event.charCode!=0) {
                if (event.which < 32) {
                    return null;
                }
                return String.fromCharCode(event.which)   /* остальные */
            }
            return null; /* специальная клавиша */
        },
        getCaretPosition: function(ctrl) {
            var CaretPos = 0;
            /* IE Support */
            if (document.selection) {
                ctrl.focus ();
                var Sel = document.selection.createRange ();
                Sel.moveStart ('character', -ctrl.value.length);
                CaretPos = Sel.text.length;
            } else {
                /* Firefox support */
                if (ctrl.selectionStart || ctrl.selectionStart == '0') {
                    CaretPos = ctrl.selectionStart;
                }
            }
            return (CaretPos);
        },
        getSelectionCount: function(input) {
            return input.selectionEnd - input.selectionStart;
        },
        getSelectionContenet: function(input) {
            return (input.value + '').substring(input.selectionStart, input.selectionEnd);
        },
        isElementCreated: function(dom) {
            if($('[name="' + dom + '"]').length > 0) {
                return true;
            } else {
                return false;
            }
        },
        isExistVariable: function(variable) {
            return typeof(variable) != 'undefined' && variable != null;
        },
        amtValid: function(e, input) {
            var this_ = this;
            e = e || event;
            if (e.ctrlKey || e.altKey || e.metaKey) {
                return;
            }
            var chr = this.getChar(e);
            if (chr == null) {
                return;
            }
            var val = input.value;
            if(chr == '.') {
                if(val.indexOf('.') >= 0) {
                    return false;
                }
                if(val.length == 0) {
                    input.value = '0.';
                    return false;
                }
            }
            var pointerPosition = val.indexOf('.');
            var isLegalCaretPosition = this_.getCaretPosition(input) <= pointerPosition;
            if(pointerPosition > -1 && val.length == pointerPosition + 3 && !isLegalCaretPosition) {
                return false;
            }
            if(chr != '.') {
                if (chr < '0' || chr > '9') {
                    return false;
                }
            }
        },
        phoneValid: function(e, input) {
            e = e || event;
            if (e.ctrlKey || e.altKey || e.metaKey) {
                return;
            }
            var chr = this.getChar(e);
            if (chr == null) {
                return;
            }
            var val = input.value;
            if(chr == '+') {
                if(this.getSelectionCount(input) == input.value.length) {
                    input.value = chr + '380';
                    return false;
                }
                if(val.indexOf('+') > -1 && this.getSelectionCount(input) < 13) {
                    return false;
                }
                if(val.length == 0) {
                    input.value = '+380';
                    return false;
                }
                /* если нет плюса, но номер уже есть */
                if(val.length > 0 && val.substr(0,1) != '+') {
                    input.value = '+' + val;
                    return false;
                }
            }
            if(chr != '+') {
                if (chr < '0' || chr > '9') {
                    return false;
                } else {
                    if(input.value == '' || input.value == '+') {
                        input.value = '+380';
                        if(chr != '3') {
                            input.value = input.value + chr;
                        }
                        return false;
                    }
                    if(this.getSelectionCount(input) == input.value.length) {
                        input.value = '+380' + chr;
                        return false;
                    }
                }
            }
        },
        numberValid: function(e, input) {
            e = e || event;
            if (e.ctrlKey || e.altKey || e.metaKey) {
                return;
            }
            var chr = this.getChar(e);
            if (chr == null) {
                return;
            }
            if (chr < '0' || chr > '9') {
                return false;
            }
        },
        dateValid: function(e, input) {
            e = e || event;
            if (e.ctrlKey || e.altKey || e.metaKey) {
                return;
            }
            var chr = this.getChar(e);
            if (chr == null) {
                return;
            }
            if(chr == '.') {
                var value = input.value + '';
                var getCount = function(){var count=0;for(var i=0;i<value.length;i++){if(value[i]=='.'){count++;}}return count;}
                if(getCount() == 2) {
                    return false;
                }
                if(value == '') {
                    input.value = '01.';
                    return false;
                }
                if(value.length==3 && value.indexOf('.')==2) {
                    input.value = value + '01.';
                    return false;
                }
                if(value.length<=3 && value.indexOf('.')<=2) {
                    input.value = value + '.01.';
                    return false;
                }
            } else {
                if (chr < '0' || chr > '9') {
                    return false;
                }
            }
        },
        arrayStringValid: function(e, input) {
            e = e || event;
            if (e.ctrlKey || e.altKey || e.metaKey) {
                return;
            }
            var chr = this.getChar(e);
            if (chr == null) {
                return;
            }
            var str = chr + '';
            if ('*()!)@+!_(@_+!(+_*()^&%$.#^;`/|<>~:&!%#"№(*)!*@({_)!(@_+!)+#*(@#)=-+*/.&()#&01234567890'.indexOf(str) > -1) {
                return false;
            }
        }
    },
	init: function(params) {
		var this_ = this;
		var i = 0;
        var j = 0;
		if(this_.private.isExistVariable(params)) {
			if(this_.private.isExistVariable(params.amt)) {
				for(i = 0; i < params.amt.length; i++) {
                    for(j = 0; j < document.getElementsByName(params.amt[i]).length; j++) {
                        this_.input[params.amt[i]] = document.getElementsByName(params.amt[i])[j];
                        if(this_.private.isExistVariable(this_.input[params.amt[i]])) {
                            this_.input[params.amt[i]].onkeypress = function(e) {
                                return this_.private.amtValid(e, this);
                            }
                        }
                    }
				}
			}
			if(this_.private.isExistVariable(params.phone)) {
				for(i = 0; i < params.phone.length; i++) {
                    for(j = 0; j < document.getElementsByName(params.phone[i]).length; j++) {
                        this_.input[params.phone[i]] = document.getElementsByName(params.phone[i])[j];
                        if(this_.private.isExistVariable(this_.input[params.phone[i]])) {
                            this_.input[params.phone[i]].onkeypress = function(e) {
                                return this_.private.phoneValid(e, this);
                            }
                        }
                    }
				}
			}
			if(this_.private.isExistVariable(params.number)) {
				for(i = 0; i < params.number.length; i++) {
                    for(j = 0; j < document.getElementsByName(params.number[i]).length; j++) {
                        this_.input[params.number[i]] = document.getElementsByName(params.number[i])[j];
                        if(this_.private.isExistVariable(this_.input[params.number[i]])) {
                            this_.input[params.number[i]].onkeypress = function(e) {
                                return this_.private.numberValid(e, this);
                            }
                        }
                    }
				}
			}
            if(this_.private.isExistVariable(params.date)) {
				for(i = 0; i < params.date.length; i++) {
                    for(j = 0; j < document.getElementsByName(params.date[i]).length; j++) {
                        this_.input[params.date[i]] = document.getElementsByName(params.date[i])[j];
                        if(this_.private.isExistVariable(this_.input[params.date[i]])) {
                            this_.input[params.date[i]].onkeypress = function(e) {
                                return this_.private.dateValid(e, this);
                            }
                        }
                    }
				}
			}
            if(this_.private.isExistVariable(params.arrayString)) {
				for(i = 0; i < params.arrayString.length; i++) {
                    for(j = 0; j < document.getElementsByName(params.arrayString[i]).length; j++) {
                        this_.input[params.arrayString[i]] = document.getElementsByName(params.arrayString[i])[j];
                        if(this_.private.isExistVariable(this_.input[params.arrayString[i]])) {
                            this_.input[params.arrayString[i]].onkeypress = function(e) {
                                return this_.private.arrayStringValid(e, this);
                            }
                        }
                    }
				}
			}
		}
		return this_;
	}
};

/* ========================================================================= */
/* отправка формы на сервер                                                 */
/* @autor Gorhover Dmitriy                                                   */
/* ------------------------------------------------------------------------- */
/*    SENDER.init({                                                          */
/*        url: 'upayment',                                                   */
/*        method: 'POST',                                                    */
/*        data: {                                                            */
/*            get: {                                                         */
/*                oper: 'rqs'                                                */
/*            },                                                             */
/*            post: {                                                        */
/*                b_card: bcard,                                             */
/*                b_card_or_acc: bcard,                                      */
/*            }                                                              */
/*        }                                                                  */
/*    });                                                                    */
/* ========================================================================= */
var SENDER = {
    private: {
        status: false,
        url: document.location.href,
        method: 'POST',
        data: {
            post: {},
            get: {}
        },
        getTemplate: function(name, value) {
            return '<input type="text" name="' + name + '" value="' + value + '"/>';
        },
        setMethod: function(params, method) {
            if(params.method) {
                this.method = params.method;
            } else {
                this.method = method;
            }
        },
        prepare: function(params) {
            var body = $('body');
            $('form[name="SENDER"]').remove();
            body.append('<form name="SENDER" style="display: none;"/>');
            var form = $('form[name="SENDER"]');
            var i;
            var count = 0;
            var url_ = this.url;
            if(this.method == 'POST') {
                for(i in this.data.get) {
                    if(count++ == 0) {
                        url_ += '?';
                    } else {
                        url_ += '&';
                    }
                    url_ += i + '=' + this.data.get[i];
                }
                for(i in this.data.post) {
                    form.append(this.getTemplate(i, this.data.post[i]));
                }
            } else {
                for(i in this.data.get) {
                    form.append(this.getTemplate(i, this.data.get[i]));
                }
            }
            form.attr('action', url_);
            form.attr('method', this.method);
            return this;
        },
        send: function(params) {
            this.prepare(params);
            if(!params.test) {
                if(!this.status) {
                    document.SENDER.submit();
                    this.status = true;
                }
            }
            return this;
        }
    },
    init: function(params) {
        if(typeof(params) == 'string') {
            this.private.url = params;
            this.private.setMethod(params, 'GET');
        } else {
            if(params.url) {
                this.private.url = params.url;
                this.private.setMethod(params, 'GET');
            }
            if(params.data.get) {
                this.private.data.get = params.data.get;
                this.private.setMethod(params, 'GET');
            }
            if(params.data.post) {
                this.private.data.post = params.data.post;
                this.private.setMethod(params, 'POST');
            }
        }
        this.private.send(params);
        return this;
    }
};

/* ========================================================================= */
/*                                                                           */
/*                                                                           */
/* ------------------------------------------------------------------------- */
/*  $KeyboardListener.init({                                                 */
/*      dom: document,                                                       */
/*      key: 'right',                                                        */
/*      action: function() {                                                 */
/*          alert(this.key);                                                 */
/*      }                                                                    */
/*  })                                                                       */
/* ========================================================================= */

var $KeyboardListener = {
    init: function(params) {
        this.private.addListener(params);
        return this;
    },
    private: {
        keys: {
            0: 'space',
            8: "backspace",
            9: "tab",
            13: "enter",
            16: "shift",
            17: "ctrl",
            18: "alt",
            19: "pause break",
            20: "caps lock",
            27: "escape",
            33: "page up",
            34: "page down",
            35: "end",
            36: "home",
            37: "left",
            38: "up",
            39: "right",
            40: "down",
            45: "insert",
            46: "delete",
            91: "left window",
            92: "right window",
            93: "select key",
            96: "numpad 0",
            97: "numpad 1",
            98: "numpad 2",
            99: "numpad 3",
            100: "numpad 4",
            101: "numpad 5",
            102: "numpad 6",
            103: "numpad 7",
            104: "numpad 8",
            105: "numpad 9",
            106: "multiply",
            107: "add",
            109: "subtract",
            110: "decimal point",
            111: "divide",
            112: "F1",
            113: "F2",
            114: "F3",
            115: "F4",
            116: "F5",
            117: "F6",
            118: "F7",
            119: "F8",
            120: "F9",
            121: "F10",
            122: "F11",
            123: "F12",
            144: "num lock",
            145: "scroll lock",
            186: ",", /* semi-colon */
            187: "=", /* equal-sign */
            188: ",", /* comma */
            189: "-", /* dash */
            190: ".", /* period */
            191: "/", /* forward slash */
            192: "`", /* grave accent */
            219: "[", /* open bracket */
            220: "\\", /* back slash */
            221: "]", /* close bracket */
            222: "'" /* single quote */
        },
        addListener: function(params) {
            var self = $KeyboardListener.private;
            if(!params.dom) {
                return $KeyboardListener;
            };
            if($(params.dom).length == 0) {
                return $KeyboardListener;
            };
            var element;
            if(typeof params.dom == 'string') {
                element = $(params.dom);
            } else if(typeof params.dom == 'object') {
                element = params.dom;
            }
            element.keypress(function(event) {
                if(self.keys[event.keyCode].indexOf(params.key)<0){
                    return this;
                }
                var target = $(event.target);
                if(target.data() != element.data()) {
                    if(params.logging) {
                        console.log(target, ' != ', element);
                    }
                    return this;
                }
                var options = {
                    ctrlKey: (event.ctrlKey==true && params.ctrl==true)
                        || (event.ctrlKey==false && params.ctrl==false)
                        || typeof params.ctrl == 'undefined',
                    altKey: (event.altKey==true && params.alt==true)
                        || (event.altKey==false && params.alt==false)
                        || typeof params.alt == 'undefined',
                    shiftKey: (event.shiftKey==true && params.shift==true)
                        || (event.shiftKey==false && params.shift==false)
                        || typeof params.shift == 'undefined'
                }
                if(typeof(params.action)=='function'
                    && options.ctrlKey
                    && options.altKey
                    && options.shiftKey
                ) {
                    params.action();
                }
                if(params.logging) {
                    console.log(event.keyCode)
                }
                return this;
            });
        }
    }
};

/* ========================================================================= */
/*                                                                           */
/*                                                                           */
/* ------------------------------------------------------------------------- */
/*                                                                           */
/* ========================================================================= */

$(document).ready(function() {
    (function($){
        $.fn.keyListener = function (key, action, dopButtons) {
            var self = this;
            if($(self).length > 0) {
                var data = {
                    dom: self
                };
                if(typeof key == 'object' && key != document) {
                    data.key = key.key == '' ? 'bodybody' : key.key;
                    data.action = (key.action || function(){});
                    if(typeof key.dopButtons == 'object') {
                        for(var i in key.dopButtons) {
                            data[i] = true;
                        }
                    }
                }
                if(typeof key == 'string' || key == document) {
                    data.key = key == '' ? 'bodybody' : key;
                }
                if(typeof action == 'function') {
                    data.action = action
                }
                if(typeof dopButtons == 'object') {
                    for(var i in dopButtons) {
                        data[i] = true;
                    }
                }
                $KeyboardListener.init(data);
            }
            return this;
        };
        return this;
    })(jQuery);
});

/* ========================================================================= */
/*                                                                           */
/*                                                                           */
/* ------------------------------------------------------------------------- */
/* $JavaTools.init();                                                        */
/* ========================================================================= */

var $JavaTools = {
    init: function() {
        if(!this.private.initStatus) {
            this.private.ArrayPrototypeFunctionsInit();
            this.private.StringPrototypeFunctionsInit();
            this.private.initStatus = true;
        }
        return this;
    },
    private: {
        initStatus: false,
        ArrayPrototypeFunctionsInit: function() {
            Array.prototype.contains = function(element) {
                return this.indexOf(element)>-1;
            }
        },
        StringPrototypeFunctionsInit: function() {
            String.prototype.contains = function(element) {
                return this.indexOf(element)>-1;
            }
        }
    }
};

